# -*- coding: utf-8 -*-
__author__ = 'xuliliang'
# @Time    : 2018/8/14 下午2:26
# @Author  : 'xuliliang'
# @Email   : xuliliang@u51.com
# @File    : permission.py
# @Software: PyCharm


from  django.shortcuts import render
from  .models import  HostPermission
from  django.db.models import  Q
from  django.core.urlresolvers import resolve ##此方法可以将url地址转换成url的name


def prem_check(request,*args,**kwargs):
	url_obj = resolve(request.path_info)
	url_name = url_obj.url_name
	print  url_obj
	perm_name = ''
	#权限必须和urlname配合使用
	if url_name:
		url_method,url_args = request.method,request.GET
		# url_args_list=[]
	# 将各个参数的值用逗号隔开组成字符串，因为数据库中是这样存的
	# 	for i in url_args:
	# 		url_args_list.append(str(url_args[i]))
	# 	url_args_list = ','.join(url_args_list)

		get_perm = HostPermission.objects.filter(Q(name='views_student_list') and Q(per_method=1))
		if get_perm:
			for i in get_perm:
				perm_name = i.name
				perm_str = 'operation.%s' % perm_name
				if request.user.has_perm(perm_str):
					print('====》权限已匹配')
					return True
			else:
				print('---->权限没有匹配')
				return  False
		else:
			return  False
	else:
		return False

def check_permission(fun):
    def wapper(request, *args, **kwargs):
        if prem_check(request, *args, **kwargs):
            return fun(request, *args, **kwargs)
        return render(request, '403.html', locals())
    return wapper